<template>
    <view class="bill-detail-container" :style="{ '--status-bar-height': statusBarHeight }">
        <!-- 自定义导航栏 - 固定在顶部 -->
        <view class="fixed-navbar">
            <custom-navbar title="账单详情" left="url" backUrl="/pages/index/index"></custom-navbar>
        </view>

        <!-- 顶部卡片 - 固定在导航栏下方 -->
        <view class="fixed-top-card">
            <view class="top-card" :class="{ 'income': isIncome }">
                <view class="amount-section">
                    <text class="amount-label">{{ isIncome ? '收入' : '支出' }}金额</text>
                    <text class="amount-value">{{ isIncome ? '+' : '-' }}{{ bill.amount ? bill.amount.toFixed(2) :
                        '0.00'
                        }}</text>
                </view>
                <view class="category-section">
                    <view class="category-icon"
                        :style="{ backgroundColor: bill.category?.color + '40' || '#FFE7B240' }">
                        <image :src="bill.category?.icon || '/static/images/default-category.png'" mode="aspectFit">
                        </image>
                    </view>
                    <text class="category-name">{{ bill.category?.name || '未分类' }}</text>
                </view>
            </view>
        </view>

        <!-- 可滚动的内容区域 -->
        <scroll-view class="scrollable-content" scroll-y="true" :style="{ height: scrollViewHeight }">
            <!-- 详情信息卡片 -->
            <view class="detail-card">
                <view class="detail-item">
                    <text class="detail-label">账单备注</text>
                    <text class="detail-value">{{ bill.remark || '无备注' }}</text>
                </view>

                <view class="divider"></view>

                <view class="detail-item">
                    <text class="detail-label">交易平台</text>
                    <view class="platform-info">
                        <image class="platform-icon" :src="bill.platform?.icon || '/static/images/default-platform.png'"
                            mode="aspectFit"></image>
                        <view class="detail-value">{{ bill.platform?.name || '未知平台' }}</view>
                    </view>
                </view>

                <view class="divider"></view>

                <!-- 添加凭证图片显示 -->
                <view class="detail-item receipt-images-item" v-if="bill.receiptImage">
                    <text class="detail-label">消费凭证</text>
                    <view class="receipt-images">
                        <view v-for="(image, index) in receiptImages" :key="index" class="receipt-image-wrapper"
                            @click="previewReceiptImage(index)">
                            <image class="receipt-image" :src="image" mode="aspectFill"></image>
                        </view>
                    </view>
                </view>

                <view class="divider" v-if="bill.receiptImage"></view>

                <view class="detail-item">
                    <text class="detail-label">交易时间</text>
                    <text class="detail-value">{{ formatDateTime(bill.transactionDate) }}</text>
                </view>

                <view class="divider"></view>

                <view class="detail-item">
                    <text class="detail-label">创建时间</text>
                    <text class="detail-value">{{ formatDateTime(bill.createTime) }}</text>
                </view>

                <view class="divider"></view>

                <view class="detail-item">
                    <text class="detail-label">最后更新</text>
                    <text class="detail-value">{{ formatDateTime(bill.updateTime) }}</text>
                </view>

                <view class="divider"></view>

                <view class="detail-item">
                    <text class="detail-label">账单编号</text>
                    <text class="detail-value id-value">{{ bill.id || '-' }}</text>
                </view>
            </view>

            <!-- 操作按钮 -->
            <view class="action-buttons">
                <button class="action-btn edit-btn" @click="editBill">
                    <uni-icons type="compose" size="18" color="#FFFFFF"></uni-icons>
                    <text>编辑账单</text>
                </button>
                <button class="action-btn delete-btn" @click="confirmDelete">
                    <uni-icons type="trash" size="18" color="#FFFFFF"></uni-icons>
                    <text>删除账单</text>
                </button>
            </view>
        </scroll-view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app'
import CustomNavbar from '@/components/CustomNavbar/CustomNavbar.vue';
import { deleteTransaction, queryTransactions } from '@/api/transaction.js';

// 详情ID
const detailId = ref('');
// 账单数据
const bill = ref({});

// 是否为收入
const isIncome = computed(() => {
    return bill.value.category && bill.value.category.spend === 0;
});

// 处理凭证图片
const receiptImages = computed(() => {
    if (!bill.value.receiptImage) return [];
    return bill.value.receiptImage.split(',');
});

// 状态栏高度
const statusBarHeight = ref('44px');
// 滚动视图高度
const scrollViewHeight = ref('calc(100vh - 300px)');

// 获取状态栏高度和计算滚动视图高度
const getStatusBarHeight = () => {
    // #ifdef APP-PLUS || MP
    const systemInfo = uni.getSystemInfoSync();
    statusBarHeight.value = (systemInfo.statusBarHeight || 44) + 'px';
    // 计算滚动视图高度：屏幕高度 - 状态栏高度 - 导航栏高度(100rpx=50px) - 顶部卡片高度(约250rpx=125px)
    const navbarHeight = 50; // 导航栏高度约50px
    const topCardHeight = 200; // 顶部卡片高度约200px
    const totalFixedHeight = (systemInfo.statusBarHeight || 44) + navbarHeight + topCardHeight;
    scrollViewHeight.value = `${systemInfo.windowHeight - totalFixedHeight}px`;
    // #endif
    // #ifdef H5
    statusBarHeight.value = '0px';
    // 在H5环境下，计算滚动视图高度
    scrollViewHeight.value = 'calc(100vh - 250px)';
    // #endif
};

// 生命周期钩子
onLoad((options) => {
    // console.log(options);
    getStatusBarHeight();
    if (options.id) {
        detailId.value = options.id;
        loadBillDetail(detailId.value);
    }
});

onShow((options) => {
    loadBillDetail(detailId.value);
});

// 加载账单详情
const loadBillDetail = async (id) => {
    try {
        const res = await queryTransactions({ id: id });
        if (res.data && (res.data.code === 200 || res.data.code === 1)) {
            bill.value = res.data.data.records[0];
            console.log('账单详情:', bill.value);
        }
    } catch (error) {
        console.error('加载账单详情失败:', error);
        uni.showToast({
            title: '加载账单详情失败',
            icon: 'none'
        });
    }
};

// 预览凭证图片
const previewReceiptImage = (index) => {
    uni.previewImage({
        urls: receiptImages.value,
        current: index
    });
};

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
    if (!dateTimeStr) return '-';

    try {
        const date = new Date(dateTimeStr);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (error) {
        console.error('日期格式化失败:', error);
        return dateTimeStr;
    }
};

// 编辑账单
const editBill = () => {
    uni.navigateTo({
        url: `/pages/transaction/add-bill?id=${bill.value.id}`
    });
};

// 确认删除
const confirmDelete = () => {
    uni.showModal({
        title: '确认删除',
        content: '确定要删除这条账单记录吗？',
        confirmColor: '#ff6b6b',
        success: async (res) => {
            if (res.confirm) {
                await deleteBill();
            }
        }
    });
};

// 删除账单
const deleteBill = async () => {
    if (!bill.value.id) {
        uni.showToast({
            title: '账单ID不存在',
            icon: 'none'
        });
        return;
    }

    try {
        uni.showLoading({
            title: '删除中...',
            mask: true
        });

        await deleteTransaction(bill.value.id);

        uni.showToast({
            title: '删除成功',
            icon: 'success'
        });

        // 使用事件总线发送刷新消息
        uni.$emit('bill_updated');

        // 返回上一页
        setTimeout(() => {
            uni.navigateBack({
                delta: 1
            });
        }, 1500);
    } catch (error) {
        console.error('删除账单失败:', error);
        uni.showToast({
            title: '删除失败',
            icon: 'none'
        });
    } finally {
        uni.hideLoading();
    }
};
</script>

<style lang="scss">
.bill-detail-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #f8f8f8;
    position: relative;
    overflow: hidden;
}

/* 固定的导航栏 */
.fixed-navbar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
}

/* 固定的顶部卡片 */
.fixed-top-card {
    position: fixed;
    top: calc(var(--status-bar-height, 44px) + 100rpx);
    /* 状态栏高度 + 导航栏高度 */
    left: 0;
    right: 0;
    z-index: 99;
    background-color: #f8f8f8;
    padding-bottom: 10rpx;
}

/* 可滚动的内容区域 */
.scrollable-content {
    position: fixed;
    top: calc(var(--status-bar-height, 44px) + 100rpx + 250rpx);
    /* 状态栏 + 导航栏 + 顶部卡片高度 */
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #f8f8f8;
}

/* 顶部卡片 */
.top-card {
    margin: 30rpx;
    padding: 40rpx;
    background-color: #ff6b6b;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 20rpx rgba(255, 107, 107, 0.2);
    display: flex;
    flex-direction: column;

    &.income {
        background-color: #4CAF50;
        box-shadow: 0 4rpx 20rpx rgba(76, 175, 80, 0.2);
    }

    .amount-section {
        display: flex;
        flex-direction: column;
        margin-bottom: 30rpx;

        .amount-label {
            font-size: 28rpx;
            color: rgba(255, 255, 255, 0.8);
            margin-bottom: 10rpx;
        }

        .amount-value {
            font-size: 60rpx;
            font-weight: bold;
            color: #FFFFFF;
        }
    }

    .category-section {
        display: flex;
        align-items: center;

        .category-icon {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
            background-color: rgba(255, 255, 255, 0.2);
            display: flex;
            justify-content: center;
            align-items: center;
            margin-right: 20rpx;

            image {
                width: 50rpx;
                height: 50rpx;
            }
        }

        .category-name {
            font-size: 32rpx;
            color: #FFFFFF;
            font-weight: 500;
        }
    }
}

/* 详情卡片 */
.detail-card {
    margin: 30rpx;
    margin-top: 20rpx;
    /* 减少顶部margin，因为已经有固定卡片了 */
    padding: 20rpx;
    background-color: #FFFFFF;
    border-radius: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .detail-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 30rpx 20rpx;

        .detail-label {
            font-size: 28rpx;
            color: #666;
        }

        .detail-value {
            flex: 1;
            font-size: 28rpx;
            color: #333;
            font-weight: 500;
            //   max-width: 60%;
            text-align: right;

            &.id-value {
                font-family: monospace;
                color: #999;
                font-size: 24rpx;
            }
        }

        .platform-info {
            display: flex;
            align-items: center;

            .platform-icon {
                width: 40rpx;
                height: 40rpx;
                margin-right: 10rpx;
            }
        }
    }

    /* 凭证图片样式 */
    .receipt-images-item {
        flex-direction: column;
        align-items: flex-start;

        .detail-label {
            margin-bottom: 20rpx;
        }

        .receipt-images {
            width: 100%;
            display: flex;
            flex-wrap: wrap;
            gap: 20rpx;

            .receipt-image-wrapper {
                width: 160rpx;
                height: 160rpx;
                border-radius: 10rpx;
                overflow: hidden;
                border: 1rpx solid #eee;
                box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

                .receipt-image {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
            }
        }
    }

    .divider {
        height: 1rpx;
        background-color: #f0f0f0;
        margin: 0 20rpx;
    }
}

/* 操作按钮 */
.action-buttons {
    margin: 0 30rpx;
    margin-bottom: 40rpx;
    /* 添加底部margin，确保滚动到底部时有足够空间 */
    display: flex;
    justify-content: space-between;

    .action-btn {
        flex: 1;
        height: 90rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 45rpx;
        font-size: 28rpx;
        color: #FFFFFF;
        margin: 0 15rpx;

        &::after {
            border: none;
        }

        text {
            margin-left: 10rpx;
        }
    }

    .edit-btn {
        background-color: #5C6BC0;
        box-shadow: 0 4rpx 10rpx rgba(92, 107, 192, 0.3);

        &:active {
            background-color: #3F51B5;
        }
    }

    .delete-btn {
        background-color: #ff6b6b;
        box-shadow: 0 4rpx 10rpx rgba(255, 107, 107, 0.3);

        &:active {
            background-color: #e05a5a;
        }
    }
}
</style>